#!/usr/bin/python
# -*- coding: utf-8 -*
import argparse
import os
import subprocess
import sys

parser = argparse.ArgumentParser()


def publish():
    print '\033[0;33m请确定代码已经提交\033[0;33m \33[0m '
    ret = raw_input('请输入(YES)继续执行发布: ')

    if ret != 'YES':
        print '发布取消'
        sys.exit(0)
    base_dir = os.getcwd()
    server_dir = base_dir + '/..'
    resource_dir = base_dir + '/../education-server/'
    target_file = server_dir + '/education-server/target/education-server-1.0.0.jar'
    publish_dir = '/data/education/dist'
    server_address = '34.210.120.136'

    print '删除服务端资源'
    call_cmd('rm -rf {0}/target'.format(server_dir))
    call_cmd('rm -rf {0}/src/main/resources/static'.format(resource_dir))
    print '创建资源文件夹'
    call_cmd('mkdir -p {0}/src/main/resources/static'.format(resource_dir))

    for name in ['h5', 'web']:
        client_dir = base_dir + '/../../' + name
        print '开始发布h5'
        print '客户端目录\t' + client_dir
        print '更新客户端资源'
        call_cmd('cd {0} && git pull'.format(client_dir))
        call_cmd('cd {0} && yarn install'.format(client_dir))
        print '更新服务端资源'
        call_cmd('cd {0} && git pull'.format(server_dir))
        print '开始打包=========================='
        print '开始打包客户端 >>>>>'
        call_cmd('cd {0} && yarn run build'.format(client_dir))
        print '客户端打包完毕 >>>>>'
        print '复制资源到服务端'
        call_cmd('cp -r {0}/dist/* {1}/src/main/resources/static/'.format(client_dir, resource_dir))

    print '服务端目录\t' + server_dir
    print '发布目录\t' + publish_dir
    print '文件名称\t' + target_file
    print '开始打包服务端'
    call_cmd('cd {0} && mvn clean package'.format(server_dir))
    print '打包完成'
    print '\n开始发布 ****************'
    print '复制资源到发布目录'

    call_cmd('scp -i /Users/hyl/Documents/work/keys/dragon.pem {0} centos@{1}:{2}'.format(target_file, server_address, publish_dir))
    # call_cmd('scp -i /Users/Angela/Documents/work/keys/dragon.pem {0} centos@{1}:{2}'.format(target_file, server_address, publish_dir))

    print '******************发布完成******************'


def call_cmd(cmd):
    if subprocess.call(cmd, shell=True) > 0:
        print "脚本执行错误!!!!!!!!!!"
        sys.exit(-1)


if __name__ == '__main__':
    reload(sys)
    sys.setdefaultencoding('utf-8')
    args = parser.parse_args()
    publish()
